package com.q.tqb.activity.mine;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.q.tqb.R;
import com.q.tqb.activity.ViewPagerImageActivity;
import com.q.tqb.activity.mine.setting.SettingBindTelActivity;
import com.q.tqb.activity.send.SendMapActivity;
import com.q.tqb.base.AppConst;
import com.q.tqb.base.BaseActivity;
import com.q.tqb.luban.Luban;
import com.q.tqb.luban.OnCompressListener;
import com.q.tqb.model.MineCardInfo;
import com.q.tqb.util.FileUtil;
import com.q.tqb.util.LogUtil;
import com.q.tqb.util.MD5Util;
import com.q.tqb.util.SPUtil;
import com.q.tqb.util.StringUtil;
import com.q.tqb.util.http.IRawResponse;
import com.q.tqb.util.http.IResponse;
import com.q.tqb.util.http.OkHttpUtil;
import com.q.tqb.util.oss.OssCallback;
import com.q.tqb.util.oss.OssService;
import com.q.tqb.view.CircleImageView;
import com.q.tqb.view.GlideLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MineDataActivity extends BaseActivity {


    @BindView(R.id.iv_head)
    CircleImageView mIvHead;


    @BindView(R.id.tv_nickname)
    TextView mTvNickname;
    @BindView(R.id.rl_name)
    RelativeLayout mRlName;
    @BindView(R.id.tv_tel)
    TextView mTvTel;
    @BindView(R.id.tv_tro)
    TextView mTvTro;
    @BindView(R.id.rl_tel)
    RelativeLayout mRlTel;
    @BindView(R.id.st_show)
    Switch mStShow;

    private String head;
    private String[] heads;
    private String nickname;
    private String mobile;
    private String signature;
    private int isShow;

    private String upPointName;
    private int uid;

    private boolean isUpdate;


    @Override
    public int getLayoutId() {
        return R.layout.activity_mine_data;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        setTitle("个人资料");

        heads = new String[1];
        updateUserData();
        initImagePicker();
        mStShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                updateShowMsg();
            }
        });
    }

    private void updateUserData() {
        head = SPUtil.getString(this, "header");
        uid = (int) SPUtil.get(this, "uid", 0);
        nickname = SPUtil.getString(this, "nickname");
        mobile = SPUtil.getString(this, "mobile");
        isShow = (int) SPUtil.get(this, "isShow", 0);
        signature = SPUtil.getString(this, "signature");
        if (isShow == 1) {
            mStShow.setChecked(true);
        }

        Glide
                .with(this)
                .load(head)
                .error(R.drawable.ic_head)
                .placeholder(R.drawable.ic_head)
                .dontAnimate()
                .into(mIvHead);

        mTvNickname.setText(nickname);
        mTvTro.setText(signature);
        if (TextUtils.isEmpty(mobile)) {
            mTvTel.setText("未绑定");
        } else {
            mTvTel.setText(mobile);
        }

    }


    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideLoader());
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(false);
        imagePicker.setSaveRectangle(true);
        imagePicker.setSelectLimit(1);
    }

    @Override
    public void onBackPressed() {
        if (isUpdate) {
            setResult(RESULT_OK);
        }
        super.onBackPressed();
    }

    @OnClick({R.id.iv_back, R.id.iv_head, R.id.rl_header, R.id.rl_name, R.id.rl_tel, R.id.rl_tro})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                if (isUpdate) {
                    setResult(RESULT_OK);
                }
                finish();
                break;
            case R.id.iv_head:
                heads[0] = head;
                intent = new Intent(MineDataActivity.this, ViewPagerImageActivity.class);
                intent.putExtra("images", heads);
                intent.putExtra("position", 0);
                startActivity(intent);
                break;
            case R.id.rl_header:
                selectDialog();
                break;
            case R.id.rl_name:
                intent = new Intent(MineDataActivity.this, MineUpdateNameActivity.class);
                intent.putExtra("content", nickname);
                intent.putExtra("type", 1);
                startActivityForResult(intent, 50);
                break;
            case R.id.rl_tro:
                intent = new Intent(MineDataActivity.this, MineUpdateNameActivity.class);
                intent.putExtra("content", signature);
                intent.putExtra("type", 2);
                startActivityForResult(intent, 50);
                break;
            case R.id.rl_tel:
                intent = new Intent(MineDataActivity.this, SettingBindTelActivity.class);
                startActivityForResult(intent, 50);
                break;
            default:
                break;
        }
    }

    private void selectDialog() {
        final String[] items = {"相机拍照", "相册选择"};
        AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(MineDataActivity.this);
        singleChoiceDialog.setTitle("选择方式");
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            ImagePicker.getInstance().setSelectLimit(1);
                            Intent intent = new Intent(MineDataActivity.this, ImageGridActivity.class);
                            // 是否是直接打开相机
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
                            startActivityForResult(intent, 100);
                        } else {
                            ImagePicker.getInstance().setSelectLimit(1);
                            Intent intent1 = new Intent(MineDataActivity.this, ImageGridActivity.class);
                            startActivityForResult(intent1, 100);
                        }
                        dialog.dismiss();
                    }
                });
        singleChoiceDialog.show();
    }

    private void upImage(String localPath) {
        mProgressDialog.show();
        String comPath = Environment.getExternalStorageDirectory() + "/tqb/head.jpg";
        Luban.with(this)
                // 传人要压缩的图片列表
                .load(localPath)
                // 忽略不压缩图片的大小
                .ignoreBy(-10)
                .setTargetDir(comPath)
                //设置回调
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        upPointName = "head/" + uid + "_" + System.currentTimeMillis() + ".JPEG";
                        OssService.asyncPutFile(upPointName, file.getAbsolutePath(), new OssCallback(new Handler(), new IRawResponse() {
                            @Override
                            public void onSuccess(String response) {
                                mProgressDialog.dismiss();
                                updateMsg();
                            }

                            @Override
                            public void onFailure(String errorMsg) {
                                showToast("请检查您的网络");
                                LogUtil.i(errorMsg);
                            }
                        }));
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();
    }

    private void updateMsg() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));
        map.put("header", AppConst.OSS_URL + upPointName);
        map.put("is_show_privacy", isShow + "");
        LogUtil.i(map.toString());
        OkHttpUtil.getInstance().post(MineDataActivity.this, AppConst.URL_UPDATE_INFO, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                isUpdate = true;
                showToast("修改成功");
                head = AppConst.OSS_URL + upPointName;
                SPUtil.put(MineDataActivity.this, "header", head);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                showToast(errorMsg);
            }
        });
    }

    private void updateShowMsg() {

        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));
        final int status;
        if (mStShow.isChecked()) {
            status = 1;
        } else {
            status = 2;
        }

        map.put("is_show_privacy", status + "");
        LogUtil.i(map.toString());
        OkHttpUtil.getInstance().post(MineDataActivity.this, AppConst.URL_UPDATE_INFO, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                SPUtil.put(MineDataActivity.this, "isShow", status);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String path = images.get(0).path;
                upImage(path);
                Glide
                        .with(MineDataActivity.this)
                        .load(path)
                        .skipMemoryCache(true)
                        .into(mIvHead);
            }
        }
        if (requestCode == 50 && resultCode == RESULT_OK) {
            isUpdate = true;
            updateUserData();
        }
    }


}


